<template>
  <el-dialog
    title="案件分发"
    :visible.sync="dialogVisible"
    custom-class="custom-dialog"
    width="50%"
    :before-close="handleClose"
    @opened="initData"
  >
    <el-row :gutter="20">
      <el-col :span="12">
        <div class="tree-panel">
          <div class="mb-10 pd-10">
            <el-input
              size="small"
              prefix-icon="el-icon-search"
              placeholder="输入关键字进行过滤"
              v-model="filterText"
            />
          </div>
          <div class="changeDepartment">
            <el-button :type="typeRecommend=='推荐部门'?'warning':''" @click="recommend" v-preventDbClick
              >推荐部门</el-button
            >
            <el-button :type="typeRecommend=='所有部门'?'warning':''" @click="Allrecommend" v-preventDbClick
              >所有部门</el-button
            >
          </div>
          <div class="tree-content of-auto pd-10" style="height: 400px">
            <div class="line-tree-panel">
              <el-tree
                v-loading="deptTreeLoading"
                ref="tree"
                class="line-tree"
                node-key="id"
                :data="deptTree"
                :default-expanded-keys="expandedKeysDept"
                :props="deptProps"
                :filter-node-method="filterNode"
                @node-click="handleNodeClick"
                :highlight-current="true"
              >
                <div
                  slot-scope="{ node }"
                  :class="
                    active == node.label
                      ? 'custom-tree-node activeBg'
                      : 'custom-tree-node'
                  "
                >
                  <div
                    :title="node.label"
                    style="
                      white-space: normal;
                      word-break: break-all;
                      height: 40px;
                      display: flex;
                      width: 100%;
                      align-items: center;
                    "
                    :style="{
                      'font-size':
                        node.level === 1
                          ? '16px'
                          : node.level === 2
                          ? '16px'
                          : '16px',
                      'font-weight': node.level === 1 ? 'bold' : '',
                    }"
                  >
                    <span
                      v-if="
                        (node.level === 3 || node.level === 4) &&
                        node.childNodes.length === 0
                      "
                      class="ml-10 mr-10 w-5 h-5 radius-50 bg-999"
                    ></span>
                    <span
                      class="tree-icon"
                      :class="
                        node.childNodes.length === 0
                          ? 'level-4'
                          : node.level === 1
                          ? 'level-1'
                          : node.level === 2
                          ? 'level-2'
                          : node.level === 3
                          ? 'level-3'
                          : 'level-4'
                      "
                    />
                    <span style="line-height: 20px">{{ node.label }}</span>
                  </div>
                </div>
              </el-tree>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="12">
        <el-form
          ref="form"
          class="query-more-form split-row"
          size="mini"
          label-width="85px"
          :model="dataForm"
          :rules="rules"
        >
          <el-row>
            <el-col :span="24">
              <el-form-item label="处置人员">
                <el-input
                  placeholder="请输入处置人员"
                  v-model="dataForm.nextUserName"
                  class="input-with-select"
                  @input="getUserList"
                >
                </el-input>
                <ul class="nextUserIdUl">
                  <li
                    class="nextUserIdLi"
                    v-for="(item, i) in userList"
                    :key="i"
                    @click="changeUserName(item)"
                  >
                    {{ item.nickName }}
                  </li>
                </ul>
                <div
                  class="pagination-panel paging"
                  v-show="userList.length > 0"
                >
                  <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="query.pageNum"
                    :page-sizes="[10, 20, 30, 40]"
                    :page-size="query.pageSize"
                    layout="total, prev, pager, next"
                    :total="query.total"
                  >
                  </el-pagination>
                </div>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="限制时间" prop="planCompleteTime">
                <el-date-picker
                  v-model="dataForm.planCompleteTime"
                  type="datetime"
                  placeholder="选择限制时间"
                  editable
                  @change="changeTime"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="分发意见" prop="opinion">
                <el-input
                  v-model="dataForm.opinion"
                  type="textarea"
                  :rows="4"
                  placeholder="请输入分发意见"
                  maxlength="500"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24"
              ><el-form-item label="推荐分发意见" prop="addressCity">
                <el-select
                  class="w-100"
                  v-model="dataForm.recommendOpinion"
                  placeholder="请选择推荐分发意见"
                  @change="changeRecommendOpinion"
                >
                  <el-option
                    v-for="item in recommendOpinionArr"
                    :key="item.id"
                    :value="item.opinion"
                    :label="item.opinion"
                  /> </el-select></el-form-item
            ></el-col>
            <el-col :span="24">
              <div class="flex-start-center">
                <el-button
                  size="mini"
                  class="submit-btn"
                  @click="handleSave()"
                  v-preventDbClick
                  >确认</el-button
                >
              </div>
            </el-col>
          </el-row>
        </el-form>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { roleDeptTreeselect } from "@/api/system/dept";
import { queryOpinionList } from "@/api/knowledgeBase.js";
import { wfmCaseDistribute2 } from "@/api/wfm/wfm.js";
import { handleList } from "@/api/user.js";
import { list as roleList } from "@/api/role.js";
import { recommend } from "@/api/case.js";
import { parseTime } from "@/utils/index";
import data from "@/views/pdf/content";
export default {
  name: "DispatchDialog2",
  props: {
    dialogVisible: {
      type: Boolean,
      default: false,
    },
    caseCode: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      deptTreeLoading: false,
      deptTree: [],
      userList: [],
      roleList: [],
      recommendOpinionArr: [],
      typeRecommend:'推荐部门',
      deptProps: {
        children: "children",
        label: "label",
      },
      query: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
      },
      timeFlag: true, //判断时间的标杆
      categoryCode: null, //权责清单编码
      expandedKeysDept: [],
      // handleSaveDisabled: false, //控制确认按钮是否为禁用状态
      filterText: "",
      usernameId: null,
      active: null,
      planCompletionTime: null,
      dataForm: {
        caseCode: "",
        opinion: "请协调快速处理！",
        planCompleteTime: "",
        nextDeptId: null,
        nextDeptName: "",
        nextRoleId: null,
        nextRoleName: "",
        nextUserId: null,
        nextUserName: "",
      },
      rules: {
        planCompleteTime: [
          { required: true, message: "选择限制时间", trigger: "change" },
        ],
        opinion: [
          { required: true, message: "请输入分发意见", trigger: "blur" },
        ],
        nextUserId: [
          { required: true, message: "请输入分发意见", trigger: "change" },
        ],
      },
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.$bus.$on("categoryCode", (data) => {
      this.categoryCode = data.categoryCode;
      this.planCompletionTime = data.planCompletionTime;
    });
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },

    // 过滤用户选择的时间
    changeTime() {
      if (Date.parse(this.dataForm.planCompleteTime) < Date.parse(new Date())) {
        this.$message.warning("选择的时间不能小于当前时间");
        this.timeFlag = false;
      } else {
        this.timeFlag = true;
      }
    },

    changeRecommendOpinion(val) {
      this.dataForm.opinion = val;
    },

    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.query.pageNum = val;
      this.getUserList();
    },

    // 推荐部门
    recommend() {
      this.typeRecommend='推荐部门'
      recommend({ categoryCode: this.categoryCode })
        .then((result) => {
          let { data } = result;
          if (data.length > 0) {
            this.deptTree = data;
            this.expandedKeysDept = data.map((item) => item.id);
            this.deptTreeLoading = false;
          } else {
            this.deptTree = data;
          }
          this.deptTreeLoading = false;
        })
        .catch();
    },

    // 所有部门
    Allrecommend() {
      this.typeRecommend='所有部门'
      roleDeptTreeselect(1)
        .then((res) => {
          this.deptTree = res.depts;
          if (res.depts && res.depts.length > 0) {
            this.expandedKeysDept = res.depts.map((item) => item.id);
          }
          this.deptTreeLoading = false;
        })
        .catch(() => {
          this.deptTreeLoading = false;
        });
    },

    changeUserName(val) {
      this.dataForm.nextUserId = val.userId;
      this.usernameId = val.userId;
      this.dataForm.nextUserName = val.nickName;
    },

    addDay(dayNumber) {
      var date = new Date();
      var ms = dayNumber * (1000 * 60 * 60 * 24);
      return parseTime(date.getTime() + ms, "{y}-{m}-{d} {h}:{m}:{s}");
    },

    addDay1(time) {
      return parseTime(time, "{y}-{m}-{d} {h}:{m}:{s}");
    },

    initData() {
      if (this.planCompletionTime) {
        this.dataForm.planCompleteTime = this.addDay1(this.planCompletionTime);
      } else {
        this.dataForm.planCompleteTime = this.addDay(2);
      }
      this.dataForm.caseCode = this.caseCode;
      this.deptTreeLoading = true;
      recommend({ categoryCode: this.categoryCode })
        .then((result) => {
          let { data } = result;
          if (data.length > 0) {
            this.deptTree = data;
            this.expandedKeysDept = data.map((item) => item.id);
            this.deptTreeLoading = false;
          } else {
            this.deptTree = data;
          }
          this.deptTreeLoading = false;
        })
        .catch();
      roleList()
        .then((res) => {
          let { code, rows, total } = res;
          if (code == 200) {
            this.roleList = rows;
          }
        })
        .catch(() => {});
      // this.getUserList();
      // 查询推荐分发意见
      queryOpinionList()
        .then((res) => {
          this.recommendOpinionArr = res.rows;
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },

    // 搜索处置人员
    getUserList() {
      if (!this.dataForm.nextDeptId && !this.dataForm.nextUserId) {
        this.$message.error("请先选择部门");
        this.dataForm.nextUserName = "";
      } else {
        (this.query.deptId = this.dataForm.nextDeptId),
          (this.query.retrieval = this.dataForm.nextUserName),
          handleList(this.query)
            .then((res) => {
              let { code, rows, total } = res;
              this.query.total = total;
              if (code == 200) {
                this.userList = rows;
              }
            })
            .catch(() => {});
      }
    },

    visibleChange(val) {
      if (val) {
        if (this.dataForm.nextDeptId === "") {
          this.$message.warning("请先选择部门");
        }
      }
    },

    handleClose() {
      this.$emit("closeDialog");
      this.clearData();
      this.userList = [];
    },

    handleSave() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // this.handleSaveDisabled = true;
          if (!this.dataForm.nextDeptId) {
            this.$message.warning("请选择部门");
          } else if (!this.timeFlag) {
            this.$message.warning("请选择正确的时间");
          } else {
            this.dataForm.planCompleteTime =
              new Date(this.dataForm.planCompleteTime).getTime() / 1000;
            this.dataForm.nextUserId = this.usernameId;
            wfmCaseDistribute2(this.dataForm)
              .then((res) => {
                let { code } = res;
                if (code == 200) {
                  this.$message.success("保存成功");
                  this.$router.push("/backlog/index");
                  this.handleClose();
                }
              })
              .catch(() => {
                this.$message.error("保存失败");
              });
          }
        }
      });
    },

    clearData() {
      this.dataForm = {
        caseCode: "",
        opinion: "",
        planCompleteTime: parseTime(
          Date.parse(new Date()),
          "{y}-{m}-{d} {h}:{m}:{s}"
        ),
        nextDeptId: null,
        nextDeptName: "",
        nextRoleId: null,
        nextRoleName: "",
        nextUserId: null,
        nextUserName: "",
      };
      this.filterText = null;
      // this.$refs["form"].clearValidate();
    },

    handleNodeClick(data, node) {
      this.dataForm.nextDeptId = data.id;
      this.dataForm.nextDeptName = data.label;
      this.active = data.label;
      this.dataForm.nextUserName = null;
      this.dataForm.nextUserId = null;
      this.userList = [];
      this.getUserList();
    },
  },
};
</script>

<style lang="scss" scoped>
.nextUserIdUl {
  list-style: none;
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  margin: 0;
  padding: 0;
  margin-top: 10px;
  .nextUserIdLi {
    margin-right: 12px;
    line-height: 20px;
    width: 22%;
    margin-bottom: 5px;
    border: 1px solid #ccc;
    cursor: pointer;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
.paging {
  margin-top: 10px;
}

.activeBg {
  background: #ddd;
}
</style>
